#include "login.h"

#include <QLabel>
#include <QPushButton>
#include <QLineEdit>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QFormLayout>
#include <QMessageBox>
#include <QMovie>
#include <QCryptographicHash>

namespace Ui {

Login::Login(QWidget* parent) : QWidget(parent) {
	/* User */
	userText = new QLineEdit(this);

	/* Password */
	passwordText = new QLineEdit();
	passwordText->setEchoMode(QLineEdit::Password);

	/* Form */
	userPassLayout = new QFormLayout();
	userPassLayout->addRow("&User",userText);
	userPassLayout->addRow("&Password",passwordText);

	/* Login button. */
	loginButton = new QPushButton("&Login");
	loginMovie = new QMovie("data/img/connect.gif");
	loginLabel = new QLabel("Opa");
	loginLabel->setMovie(loginMovie);

	cancelButton = new QPushButton("&Cancel");
	cancelButton->setDisabled(true);

	loginLayout = new QHBoxLayout();
	loginLayout->addStretch();
	loginLayout->addWidget(loginButton);
	loginLayout->addWidget(cancelButton);
	loginLayout->addWidget(loginLabel);
	loginLayout->addStretch();

	/* Main Layout */
	mainLayout = new QVBoxLayout();
	mainLayout->addLayout(userPassLayout);
	mainLayout->addLayout(loginLayout);
	mainLayout->addStretch();

	setLayout(mainLayout);
	connect(passwordText, SIGNAL(returnPressed()),this,SLOT(login()));
	connect(loginButton, SIGNAL(clicked()),this,SLOT(login()));
	connect(cancelButton, SIGNAL(clicked()),this,SLOT(cancelled()));
}

Login::~Login() { 
	delete loginButton;
	delete loginMovie;
	delete loginLabel;

	delete userText;
	delete passwordText;
	delete userPassLayout;

	delete loginLayout;
	delete mainLayout;
}

void Login::login() {
	loginLabel->show();
	loginMovie->start();
	loginButton->setDisabled(true);
	cancelButton->setEnabled(true);
	passwordText->setDisabled(true);
	userText->setDisabled(true);
	emit tryToConnect(userText->text(), QString(QCryptographicHash::hash(passwordText->text().toUtf8(), QCryptographicHash::Md5)));
	connect(cancelButton, SIGNAL(clicked()),this,SIGNAL(cancelConnection()));
}

void Login::cancelled() {
	loginMovie->stop();
	loginLabel->hide();
	loginButton->setEnabled(true);
	cancelButton->setDisabled(true);
	passwordText->setEnabled(true);
	userText->setEnabled(true);
}

void Login::refused() {
	loginMovie->stop();
	loginLabel->hide();
	QMessageBox::critical(this,"Connection Error!","Check your login and password.");
	loginButton->setEnabled(true);
	cancelButton->setDisabled(true);
	passwordText->setEnabled(true);
	userText->setEnabled(true);
}

}

